<template name="locator">
	<view class="weui-cells weui-cells_after-title">
		<view class="weui-cell weui-cell_input" @click="showRegionSelector">
			<view class="weui-cell__hd">
				<view class="weui-label">地区<text style="color:red;">*</text></view>
			</view>
			<view class="weui-cell__bd">
				<input class="weui-input" placeholder="点击选择" type="text" maxlength="40" :value="regionText" disabled="true"></input>
			</view>
		</view>
		<view class="weui-cell weui-cell_input" @click="chooseFromMap">
			<view class="weui-cell__hd">
				<view class="weui-label">位置</view>
			</view>
			<view class="weui-cell__bd">
				<input class="weui-input" placeholder="从地图选择" type="text" maxlength="40" :value="locationTxt" disabled="true"></input>
			</view>
			<view class="weui-cell__ft">
				<text class="iconfont iconlocate"></text>
			</view>
		</view>
		<location-map-chooser v-show="showMapLocator" :zoom="mapZoom" :gps="gpsPointStr4Search" @chooselocation="locationSelected" @cancelchoose="cancelMap"></location-map-chooser>
		<iframe v-if="auto" id="geoPage" width=0 height=0 frameborder=0 style="display:none;" scrolling="no" src="https://apis.map.qq.com/tools/geolocation?key=BTIBZ-UHNL2-DJCUW-C2UCH-CDQCS-4IBMW&referer=Pray-H5">
		</iframe>
		<simple-address ref="simpleAddress" :pickerValueDefault="regionGlobal.slice(1)" @onConfirm="regionChange" customItem="全部"
		 themeColor='#007AFF'></simple-address>
	</view>
</template>

<script>
	let autoLocation
	window.addEventListener('message', function(event) {
		if (event.data && event.data.module == 'geolocation') {
			// console.log(event.data)
			autoLocation = event.data
		}
	}, false);
	import LocationMapChooser from "./map-locator.vue"
	import simpleAddress from "@/components/simple-address/simple-address.nvue"
	import sys from '../common/sys.js'
	import utils from '../common/function.js'

	export default {
		name: "locator",
		components: {
			simpleAddress,
			LocationMapChooser
		},
		props: {
			region: {
				type: Array,
			},
			location: {
				type: String,
			},
			customItem: {
				type: String,
			},
			gps: {
				type: Array,
			},
			auto:{
				type:Boolean,
				default: true,
			}
		},
		data() {
			return {
				gpsPoint: this.gps,
				locationTxt: this.location,
				showMapLocator: false,
				regionGlobal: this.region,
			};
		},
		computed: {
			regionText: function() {
				console.log(this.regionGlobal)
				if (this.regionGlobal && this.regionGlobal.length == 4) {
					let [country, province, city, district] = this.regionGlobal
					if (country == '中国') {
						let cr = new utils.ChinaRegion(province, city, district)
						let cityTxt = cr.cityShort() ? ' ' + cr.cityShort() : ''
						if (province==city) cityTxt=''
						if (district == '全部' || district == city) return cr.provinceShort() + cityTxt
						else return district + ' (' + cr.provinceShort() + cityTxt + ')'
					} else {
						return this.region.join(', ')
					}
				} else {
					return '点击选择'
				}
			},
			gpsPointStr4Search: function(){
				if(this.gpsPoint && this.gpsPoint.length==2) return this.gpsPoint[1]+','+this.gpsPoint[0]
				else return ''
			},
			mapZoom: function(){
				if(this.locationTxt) return 15
				if(this.regionGlobal && this.regionGlobal.length == 4) {
					let cnt = this.regionGlobal.filter(i=>i=='全部').length
					switch(cnt){
						case 0: return 12 // whole district
						case 1: return 8 // whole city (9, 10 maybe better, but is unavailable (has bug))
						case 2: return 6 // whole province
						case 3: return 4 // whole china
						default: return 1 // should not happen
					}
				}else return 15
			}
		},

		methods: {
			autoLocate: async function() {
				if(autoLocation){
					let loc = autoLocation
					if(loc.nation=='中国'){
						this.regionGlobal = [loc.nation, loc.province, loc.city?loc.city:'全部', loc.district?loc.district:'全部']
					}else{
						this.regionGlobal = [loc.nation, loc.province, loc.city, loc.district]
					}
					this.gpsPoint = [loc.lng, loc.lat]
					this.locationTxt = ''
					this.$emit('placeupdate', {
						region: this.regionGlobal,
						gps: this.gpsPoint
					})
				}else{
					sys.toast('定位失败')
				}
			},
			showRegionSelector: function() {
				this.$refs.simpleAddress.open();
			},
			regionChange: async function(e) {
				let region = e.label.split('-')
				let regionStr = region.join('').replace(/全部/g,'')
				region.unshift('中国')
				this.regionGlobal = region
				let response = await sys.geocoding(regionStr)
				if(response && response.errMsg == 'request:ok'){
					let loc = response.data
					this.gpsPoint = [loc.result.location.lng, loc.result.location.lat]
				}
				this.locationTxt = ''
				this.$emit('placeupdate', {
					region: this.regionGlobal,
					gps: this.gpsPoint
				})
			},
			locationSelected: async function(e) {
				this.showMapLocator = false
				if(e.poiname && e.poiname!='我的位置'){
					this.locationTxt = e.poiname
				}else{
					this.locationTxt = ''
				}
				this.gpsPoint = [e.latlng.lng, e.latlng.lat]
				let loc = await sys.regeocoding(e.latlng.lng, e.latlng.lat)
				if(loc && loc.errMsg == 'request:ok'){
					let ac = loc.data.result.addressComponent
					this.regionGlobal = [ac.country, ac.province, ac.city, ac.district]
					this.$emit('placeupdate', {
						region: this.regionGlobal,
						gps: this.gpsPoint,
						location: this.locationTxt
					})
				}
			},
			cancelMap: function() {
				this.showMapLocator = false
			},
			chooseFromMap: utils.freq(800, function() {
				sys.toast_loading('加载地图')
				this.showMapLocator = true
			}),
		},
	}
</script>

<style>
	@import "../static/weui.min.css";

	.map {
		position: fixed;
		width: 100%;
		height: 100%;

	}
</style>
